// --- 金额处理工具函数 ---

/**
 * 将数字金额转换为中文大写金额
 * @param {number} amount - 要转换的数字金额
 * @returns {string} 中文大写金额
 */
function amountToChinese(amount) {
  if (amount === null || amount === undefined || isNaN(amount)) return '';
  
  const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  const units = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟'];
  const decimals = ['角', '分'];
  
  // 将金额转换为字符串，分割整数和小数部分
  const amountStr = amount.toFixed(2);
  const [integerPart, decimalPart] = amountStr.split('.');
  
  // 处理整数部分
  let chineseStr = '';
  let zeroFlag = false;
  
  for (let i = 0; i < integerPart.length; i++) {
    const digit = parseInt(integerPart[i], 10);
    const position = integerPart.length - i - 1;
    
    if (digit === 0) {
      zeroFlag = true;
    } else {
      if (zeroFlag && i > 0) {
        chineseStr += digits[0];
        zeroFlag = false;
      }
      chineseStr += digits[digit] + units[position];
    }
  }
  
  // 处理整数部分的特殊情况
  if (chineseStr === '') {
    chineseStr = digits[0];
  }
  
  chineseStr += '圆';
  
  // 处理小数部分
  const jiao = parseInt(decimalPart[0], 10);
  const fen = parseInt(decimalPart[1], 10);
  
  if (jiao === 0 && fen === 0) {
    chineseStr += '整';
  } else {
    if (jiao !== 0) {
      chineseStr += digits[jiao] + decimals[0];
    } else if (chineseStr !== digits[0] + '圆') {
      chineseStr += digits[0];
    }
    
    if (fen !== 0) {
      chineseStr += digits[fen] + decimals[1];
    }
  }
  
  return chineseStr;
}

/**
 * 格式化货币金额显示
 * @param {number} amount - 要格式化的金额
 * @returns {string} 格式化后的金额字符串
 */
function formatCurrency(amount) {
  if (amount === null || amount === undefined || isNaN(amount)) return '¥0.00';
  return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

// --- 数据计算和统计函数 ---

/**
 * 计算礼金统计信息
 * @param {Array} gifts - 礼金记录数组
 * @returns {Object} 包含总金额、总人数等统计信息的对象
 */
function calculateStats(gifts) {
  const decryptedGifts = gifts.filter(g => g.data);
  
  const totalAmount = decryptedGifts.reduce((sum, gift) => sum + (gift.data?.amount || 0), 0);
  const totalGivers = decryptedGifts.length;
  
  // 按类型统计
  const typeStats = decryptedGifts.reduce((stats, gift) => {
    const type = gift.data?.type || '其他';
    if (!stats[type]) {
      stats[type] = { count: 0, amount: 0 };
    }
    stats[type].count += 1;
    stats[type].amount += gift.data?.amount || 0;
    return stats;
  }, {});
  
  return {
    totalAmount,
    totalGivers,
    typeStats
  };
}

// --- 加密和解密相关函数 ---

/**
 * 将 IndexedDB 的请求对象转换为 Promise，简化异步操作
 * @param {IDBRequest} request - IndexedDB 请求对象
 * @returns {Promise<any>}
 */
function promisifyRequest(request) {
  return new Promise((resolve, reject) => {
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

/**
 * 初始化 IndexedDB 数据库
 * @returns {Promise<IDBDatabase>}
 */
function initIndexedDB() {
  return new Promise((resolve, reject) => {
    try {
      const request = indexedDB.open("GiftRegistryDB", 1);

      request.onerror = (event) => {
        console.error("数据库打开失败:", event.target.errorCode);
        reject(new Error("无法访问浏览器数据库。这可能是由于您使用了隐私浏览模式或禁用了相关功能。"));
      };

      request.onsuccess = (event) => {
        resolve(event.target.result);
      };

      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        db.createObjectStore("events", { keyPath: "id", autoIncrement: true });
        const giftStore = db.createObjectStore("gifts", { keyPath: "id", autoIncrement: true });
        // 为 'gifts' 创建索引，方便按事项ID查询
        giftStore.createIndex("eventId", "eventId", { unique: false });
      };
    } catch (e) {
      console.error("IndexedDB 初始化失败:", e);
      reject(new Error("您的浏览器不支持或已禁用 IndexedDB，本应用无法运行。"));
    }
  });
}

// --- DOM 操作辅助函数 ---

/**
 * 创建模态框并显示
 * @param {string} title - 模态框标题
 * @param {string} content - 模态框内容的 HTML 字符串
 * @param {Array<object>} actions - 包含按钮配置的数组, {text, class, handler, keepOpen}
 * @param {Object} options - 配置项
 */
function createModal(title, content, actions = [], options = {}) {
  const { modalContainer, modalTitle, modalContent, modalActions } = getModalElements();
  
  if (!modalContainer) return;
  
  modalTitle.innerHTML = title;
  modalContent.innerHTML = content;
  modalActions.innerHTML = "";

  modalActions.classList.remove("hidden");

  actions.forEach((action) => {
    const button = document.createElement("button");
    button.textContent = action.text;
    button.className = action.class;
    // 为按钮增加 ID，以便其他函数可以引用
    if (action.id) {
      button.id = action.id;
    }
    button.onclick = () => {
      action.handler?.();
      if (!action.keepOpen) closeModal();
    };
    modalActions.appendChild(button);
  });
  
  // 应用配置
  if (options.large) {
    modalContainer.querySelector('.modal')?.classList.add('modal-large');
  } else {
    modalContainer.querySelector('.modal')?.classList.remove('modal-large');
  }
  
  modalContainer.classList.remove("hidden");
  document.body.style.overflow = "hidden"; // 禁止背景滚动
}

/**
 * 关闭模态框
 */
function closeModal() {
  const modalContainer = document.getElementById("modal-container");
  if (!modalContainer) return;
  
  modalContainer.classList.add("hidden");
  
  const modal = modalContainer.querySelector('.modal');
  if (modal) {
    modal.classList.remove("modal-large"); // 恢复默认大小
  }
  
  document.body.style.overflow = "auto"; // 恢复背景滚动
}

/**
 * 获取模态框相关的 DOM 元素
 * @returns {Object} 包含模态框各个部分的 DOM 元素引用
 */
function getModalElements() {
  return {
    modalContainer: document.getElementById("modal-container"),
    modalTitle: document.getElementById("modal-title"),
    modalContent: document.getElementById("modal-content"),
    modalActions: document.getElementById("modal-actions")
  };
}

/**
 * 显示提示弹窗
 * @param {string} title - 弹窗标题
 * @param {string} message - 弹窗内容
 * @param {function} [callback] - 用户点击"确定"后执行的回调函数
 */
function showAlert(title, message, callback = null) {
  createModal(title, `<p>${message}</p>`, [
    {
      text: "确定",
      class: "themed-button-primary px-4 py-2 rounded",
      handler: () => {
        if (typeof callback === "function") callback();
      },
    },
  ]);
}

/**
 * 显示通知消息
 * @param {string} message - 通知消息内容
 * @param {string} type - 通知类型 (success, error, info)
 * @param {number} duration - 显示持续时间(毫秒)
 */
function showNotification(message, type = 'info', duration = 3000) {
  // 检查是否已存在通知元素，如果不存在则创建
  let notificationContainer = document.getElementById('notification-container');
  if (!notificationContainer) {
    notificationContainer = document.createElement('div');
    notificationContainer.id = 'notification-container';
    notificationContainer.style.position = 'fixed';
    notificationContainer.style.top = '20px';
    notificationContainer.style.right = '20px';
    notificationContainer.style.zIndex = '9999';
    document.body.appendChild(notificationContainer);
  }
  
  // 创建通知元素
  const notification = document.createElement('div');
  notification.className = `p-4 rounded-lg shadow-lg mb-2 transform transition-all duration-300 ease-in-out opacity-0 translate-x-full`;
  
  // 设置样式
  switch (type) {
    case 'success':
      notification.style.backgroundColor = '#4caf50';
      notification.style.color = 'white';
      break;
    case 'error':
      notification.style.backgroundColor = '#f44336';
      notification.style.color = 'white';
      break;
    case 'info':
    default:
      notification.style.backgroundColor = '#2196f3';
      notification.style.color = 'white';
      break;
  }
  
  notification.textContent = message;
  notificationContainer.appendChild(notification);
  
  // 显示通知
  setTimeout(() => {
    notification.classList.remove('opacity-0', 'translate-x-full');
  }, 10);
  
  // 自动关闭
  setTimeout(() => {
    notification.classList.add('opacity-0', 'translate-x-full');
    setTimeout(() => {
      notification.remove();
    }, 300);
  }, duration);
}

// --- 文件处理函数 ---

/**
 * 读取文件并转换为 Base64 编码
 * @param {File} file - 要读取的文件
 * @returns {Promise<string>} 文件的 Base64 编码字符串
 */
function readFileAsBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
    reader.readAsDataURL(file);
  });
}

/**
 * 验证封面图文件大小是否有效
 * @param {File} file - 要验证的文件
 * @param {number} maxSize - 最大允许大小(字节)
 * @returns {boolean} 文件大小是否有效
 */
function isValidFileSize(file, maxSize) {
  if (!file || file.size > maxSize) {
    showAlert("文件过大", `请上传小于 ${(maxSize / (1024 * 1024)).toFixed(1)}MB 的图片`);
    return false;
  }
  return true;
}

// --- 工具类导出 --- (为了兼容旧代码，不使用模块化导出)
// 将工具函数挂载到全局对象上
window.utils = {
  amountToChinese,
  formatCurrency,
  calculateStats,
  promisifyRequest,
  initIndexedDB,
  createModal,
  closeModal,
  getModalElements,
  showAlert,
  showNotification,
  readFileAsBase64,
  isValidFileSize
};